package com.lechuang.cunpinke.db.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.lechuang.cunpinke.bean.LogBean;
import com.lechuang.cunpinke.db.DBManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：尹松涛
 * 邮箱：yinsongtaoshmily@outlook.com
 * 日期：2017/6/23
 * 时间：11-00
 */

public class LogDao {
    public final static String TABLE_NAME = "log_info";
    public final static String TABLE_COLUMN_ID = "id";
    public final static String TABLE_COLUMN_TAG = "tag";
    public final static String TABLE_COLUMN_MSG = "msg";
    public final static String TABLE_COLUMN_TIME = "time";

    public void insertLogs(List<LogBean> logs) {
        if (logs == null || logs.isEmpty()) return;
        SQLiteDatabase db = DBManager.getInstance().openDatabase();
        for (LogBean log : logs) {
            ContentValues values = new ContentValues();
            values.put(TABLE_COLUMN_TAG, log.tag);
            values.put(TABLE_COLUMN_MSG, log.msg);
            values.put(TABLE_COLUMN_TIME, log.time);
            db.insert(TABLE_NAME, null, values);
        }
        DBManager.getInstance().closeDatabase();
    }

    public List<LogBean> getAllLogs() {
        List<LogBean> logs = null;
        SQLiteDatabase db = DBManager.getInstance().getReadDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{TABLE_COLUMN_TAG, TABLE_COLUMN_MSG, TABLE_COLUMN_TIME}, null, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            logs = new ArrayList<>();
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                LogBean log = new LogBean();
                log.tag = cursor.getString(0);
                log.msg = cursor.getString(1);
                log.time = cursor.getLong(2);
                logs.add(log);
            }
        }
        if (cursor != null)
            cursor.close();
        return logs;
    }

    public void clear() {
        SQLiteDatabase db = DBManager.getInstance().openDatabase();
        db.delete(TABLE_NAME, null, null);
        DBManager.getInstance().closeDatabase();
    }
}
